const baseUrl = 'http://124.222.15.231:6218'

export function LoginApi(data) {
  return new Promise((resolve, reject) => {
    fetch(`${baseUrl}/user/login`, {
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(data),
      method: 'POST',
    })
      .then(async (res) => {
        const result = await res.json()
        console.log('登录接口返回', result)
        resolve(result)
      })
      .catch((e) => {
        reject(e)
      })
  })
}

export function RegisterApi(data) {
  return new Promise((resolve, reject) => {
    fetch(`${baseUrl}/user/reg`, {
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(data),
      method: 'POST',
    })
      .then(async (res) => {
        const result = await res.json()
        console.log('注册接口：', result)
        resolve(result)
      })
      .catch((e) => {
        reject(e)
      })
  })
}

export function CreateNewChat() {
  return new Promise((resolve, reject) => {
    fetch(`${baseUrl}/user/newtopic`, {
      headers: {
        'content-type': 'application/json',
        token: localStorage.getItem('token'),
      },
      method: 'POST',
    })
      .then(async (res) => {
        const result = await res.json()
        console.log('新增会话成功：', result)
        resolve(result)
      })
      .catch((e) => {
        reject(e)
      })
  })
}

export function SendQuestionAPI(data, navigate, signal) {
  const token = localStorage.getItem('token')
  try {
    return new Promise(async (resolve, reject) => {
      if (!token) {
        navigate('/')
        reject()
        return
      }
      await fetch(`${baseUrl}/user/chat`, {
        headers: {
          'content-type': 'application/json',
          token,
        },
        method: 'POST',
        body: JSON.stringify(data),
        signal,
      })
        .then((response) => {
          if (!response.ok) {
            reject()
            throw new Error('网络请求出错！')
          }
          resolve(response)
        })
        .catch((e) => {
          if (e instanceof DOMException && e.name == 'AbortError') {
            // …
          } else {
            reject(e)
          }
        })
    })
  } catch (e) {
    if (e instanceof DOMException && e.name == 'AbortError') {
      console.log("!")
      // …
    } else {
      reject(e)
    }
  }
}

export function GetExampleAPI() {
  return new Promise((resolve, reject) => {
    resolve({
      success: true,
      data: [
        {
          id: 1,
          content: '今天天气怎么样，我出门怎么搭配比较合适',
        },
        {
          id: 2,
          content: '我想了解2024年全国各地公积金贷款规则',
        },
        {
          id: 3,
          content: '（近日爆火的AI游戏）哄哄模拟器“最长”攻略',
        },
      ],
    })
  })
}
